package com.ruoyi.system.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.Socket;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.json.JSON;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.AppResnetPic;
import com.ruoyi.system.service.IAppResnetPicService;

import sun.misc.BASE64Decoder;

/**
 * 图片识别 信息操作处理
 * 
 * @author ruoyi
 * @date 2019-08-05
 */
@Controller
@RequestMapping("/system/appResnetPic")
public class AppResnetPicController extends BaseController
{
    private String prefix = "system/appResnetPic";
	
	@Autowired
	private IAppResnetPicService appResnetPicService;
	
	@RequiresPermissions("system:appResnetPic:view")
	@GetMapping()
	public String appResnetPic()
	{
	    return prefix + "/appResnetPic";
	}
	
	/**
	 * 查询图片识别列表
	 */
	@RequiresPermissions("system:appResnetPic:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(AppResnetPic appResnetPic)
	{
		startPage();
        List<AppResnetPic> list = appResnetPicService.selectAppResnetPicList(appResnetPic);
		return getDataTable(list);
	}
	
	
	/**
	 * 导出图片识别列表
	 */
	@RequiresPermissions("system:appResnetPic:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AppResnetPic appResnetPic)
    {
    	List<AppResnetPic> list = appResnetPicService.selectAppResnetPicList(appResnetPic);
        ExcelUtil<AppResnetPic> util = new ExcelUtil<AppResnetPic>(AppResnetPic.class);
        return util.exportExcel(list, "appResnetPic");
    }
	
	/**
	 * 新增图片识别
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	public void saveImg(String imageBase64, String imgFilePath) {
		System.out.println("imgFilePath:"+imgFilePath);
		BASE64Decoder decoder = new BASE64Decoder();
		String baseValue = imageBase64.replaceAll(" ", "+");// 前台在用Ajax传base64值的时候会把base64中的+换成空格，所以需要替换回来。
		byte[] b;
		try {
			b = decoder.decodeBuffer(baseValue.replace("data:image/jpeg;base64,", ""));
			imageBase64 = imageBase64.replace("base64,", "");
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			// 生成jpeg图片
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();
			
		} catch (IOException e1) {
			e1.printStackTrace();
		}// 去除base64中无用的部分
		
	}

	/**
	 * 新增保存图片识别
	 */
	@RequiresPermissions("system:appResnetPic:add")
	@Log(title = "图片识别", businessType = BusinessType.INSERT)
	@PostMapping("/add2")
	@ResponseBody   
	public AjaxResult addSave2(MultipartFile upload, String fileName)
	{	

        //指定本地文件夹存储图片
        try {


        	File imgfnew = new File(Global.getUploadPath() + "/" + fileName);

			upload.transferTo(imgfnew);


			while(!imgfnew.exists()) {
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
			System.out.println(Global.getUploadPath() + "/" + fileName);
        	return success();
		} catch (Exception e) {
			e.printStackTrace();
		} 
        return error();
	}
	
	/**
	 * 新增保存图片识别
	 */
	@RequiresPermissions("system:appResnetPic:add")
	@Log(title = "图片识别", businessType = BusinessType.INSERT)
	@PostMapping("/add3")
	@ResponseBody   
	public AjaxResult addSave3(String fileName)
	{	
		System.out.println("addSave3 fileName:"+fileName);

        Socket socket = null;
        try {
        	AppResnetPic appResnetPic = new AppResnetPic();
			
    		//远程调用socket接口
			socket = getConnection("127.0.0.1", 8121);
			socket.setSoTimeout(10000);
			String resultStr = send(socket, Global.getUploadPath() + "/" + fileName);
			System.out.println("socket resultStr="+resultStr);
			String str = resultStr.trim().replaceAll("'", "\"");
			JSONObject data = JSON.unmarshal(str, JSONObject.class);
			
			String predict_values = data.getStr("predict_values");
			String logit_values = data.getStr("logit_values");
			String names = data.getStr("names");
			if (names.startsWith("other"))
				appResnetPic.setNames("other");
			else {
				appResnetPic.setNames(names);
			}

			appResnetPic.setPicLocation("/profile/upload/" + fileName);
			appResnetPic.setPredictValues(predict_values);
			appResnetPic.setLogitValues(logit_values);
			
			if (appResnetPicService.insertAppResnetPic(appResnetPic) > 0) {
				
				return success();
			}

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("image file path："+fileName);
			return AjaxResult.error("error, Failed to link remote service。");
		} finally {
			close(socket);
		}
        return error();	
        
	}
	/**
	 * 新增保存图片识别
	 */
	@RequiresPermissions("system:appResnetPic:add")
	@Log(title = "图片识别", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody   
	public AjaxResult addSave(String imageBase64, String logoUpload)
	{		
		
		
		
		String ns[] = logoUpload.split("\\.");
		String file_type = ns[ns.length-1];
		
		String file_name = System.currentTimeMillis()+"."+file_type;
		//String imgFilePath = "E:\\项目\\项目-深度学习TensorFlow\\随书资源\\代码\\models\\research\\slim\\"+file_name;
		String imgFilePath = "/opt/models/research/slim/"+file_name;
		saveImg(imageBase64, imgFilePath);
			
		
		
		AppResnetPic appResnetPic = new AppResnetPic();
			
		//远程调用socket接口
		Socket socket = null;
		try {
			socket = getConnection("127.0.0.1", 8121);
			String resultStr = send(socket, file_name);
			String str = resultStr.trim().replaceAll("'", "\"");
			JSONObject data = JSON.unmarshal(str, JSONObject.class);
			
			String predict_values = data.getStr("predict_values");
			String logit_values = data.getStr("logit_values");
			String names = data.getStr("names");
             
			// {'D:/profile/upload/2019/07/11/568c40c2c5f9720242daf04bde7bf48a.png':
			// {'sexy': 0.022963677, 'drawings': 0.025316697, 'hentai': 0.1454492, 'porn':
			// 0.23056108, 'neutral': 0.57570934}}
			
			appResnetPic.setPicLocation("/profile/upload/"+file_name);
			appResnetPic.setPredictValues(predict_values);
			appResnetPic.setLogitValues(logit_values);
			appResnetPic.setNames(names);
			
			if (appResnetPicService.insertAppResnetPic(appResnetPic) > 0) {
				saveImg(imageBase64, Global.getUploadPath()+"/"+file_name);
				return success();
			}

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("image file path："+imgFilePath);
			return AjaxResult.error("error, Failed to link remote service。");
		} finally {
			close(socket);
		}
		
		return error();
		
	}

	/**
	 * 修改图片识别
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Integer id, ModelMap mmap)
	{
		AppResnetPic appResnetPic = appResnetPicService.selectAppResnetPicById(id);
		mmap.put("appResnetPic", appResnetPic);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存图片识别
	 */
	@RequiresPermissions("system:appResnetPic:edit")
	@Log(title = "图片识别", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(AppResnetPic appResnetPic)
	{		
		return toAjax(appResnetPicService.updateAppResnetPic(appResnetPic));
	}
	
	/**
	 * 删除图片识别
	 */
	@RequiresPermissions("system:appResnetPic:remove")
	@Log(title = "图片识别", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(appResnetPicService.deleteAppResnetPicByIds(ids));
	}
	
	
	public Socket getConnection(String ip, int port) {
		Socket socket = null;
		try {
			socket = new Socket(ip, port);
			socket.setSoTimeout(30000);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return socket;
	}

	/*
	 * 发送报文
	 */
	public String send(Socket socket, String cmd) {
		InputStream in = null;
		OutputStream out = null;
		BufferedReader br = null;
		try {
			// in代表服务器到客户端的流
			in = socket.getInputStream();
			// 代表客户端到服务器的流
			out = socket.getOutputStream();

			// 输入执行命令
			PrintWriter printWriter = new PrintWriter(out, true);
			printWriter.write(cmd);
			printWriter.flush();

			// 接收执行命令结果
			br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			return br.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	/*
	 * 关闭socket连接
	 */
	public void close(Socket socket) {
		if (socket != null) {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
}
